﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Collections;
using System.Diagnostics;
using Winforms = System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Xml.Serialization;

namespace WebReader
{
    
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class IXBTWindow : Window
    {

        

        private string adress = "http://www.ixbt.com/news/hard/";
        public string loadedText = "";

        ArrayList arrLinks = new ArrayList();       
        ArrayList arrLinksNew = new ArrayList();

        public Articles articles = new Articles();
        Articles articlesCurr = new Articles();

        string xmlName = "\\xbt_Articles.xml";
        public string strKeyIxbt = "nl_nw_link";

        Settings s;
        Winforms.Timer tmLink = new Winforms.Timer();
        Winforms.Timer tmAbort = new Winforms.Timer();

        Hyperlink hlCurr;
        int hintCurr = 0;
        string filePath = "";

        public int runCycle = 0;

        public IXBTWindow(ref Settings _s, string _filePath)
        {
            s = _s;
            filePath = _filePath;
            InitializeComponent();
            FuncDownLoadText();
            SetTimerAbort();
            FuncFillLinksIxbt();                
            SetTimer();    

        }

        public void DgDownLoadText(Object myObject, EventArgs myEventArgs)
        {
            ThreadPool.QueueUserWorkItem(DownLoadText);
        }

        public void DownLoadText(Object myObject)
        {
            FuncDownLoadText();
        }

        public void FuncDownLoadText()
        {
            try
            {
                WebClient wc = new WebClient();
                string str = Encoding.UTF8.GetString(Encoding.Convert(Encoding.GetEncoding(1251), Encoding.UTF8, wc.DownloadData(adress)));
                if (str != "") { loadedText = str; }
            }
            catch
            {
            }
        }
        public void SetTimer()
        {
            Winforms.Timer tm = new Winforms.Timer();
            tm.Interval = 600000;            
            tm.Tick += new EventHandler(FillLinksIxbt);
            tm.Start();
            Winforms.Timer tmText = new Winforms.Timer();
            tmText.Interval = 500000;
            tmText.Tick += new EventHandler(DgDownLoadText);
            tmText.Start();

        }

        public void FillLinks(Object myObject)
        {
            FuncFillLinksIxbt();
        }

        public void FuncFillLinksIxbt()
        {


            DeSerial();

            try
            {
                if (loadedText != "")
                {
                    string text = loadedText;

                    articlesCurr.articles.Clear();
                    tbMain.Inlines.Clear();
                    int numCurr = 0;
                    int num = 0;
                    int counter = 0;
                    while ((num = text.IndexOf(strKeyIxbt, numCurr)) > 0 && runCycle == 1)
                    {

                        int numLink = 0;
                        int count = 0;
                        int startInd = num;
                        while ((numLink = text.IndexOf("href", startInd, count)) == -1)
                        {
                            startInd--;
                            count = num - startInd;
                        }


                        int numLinkEnd = text.IndexOf("\"", startInd + 7);
                        string name = "";
                        string link = "";
                        link = text.Substring(numLink + 6, (numLinkEnd - numLink - 6));
                        numLink = numLinkEnd;
                        numLink = text.IndexOf(">", numLinkEnd + 1);
                        numLinkEnd = text.IndexOf("<", numLink);
                        name = text.Substring(numLink + 1, (numLinkEnd - numLink - 1));
                        if (name != "" && !arrLinksNew.Contains(link))
                        {
                            AddLink("http://www.ixbt.com" + link, name);
                            numCurr = numLinkEnd;
                            counter++;
                        }
                        if (counter > 9)
                        {
                            articles = articlesCurr;
                            Serial();

                            ChangeViewLinks();
                            return;
                        }

                        num = 0;
                    }
                }
            }
            catch
            {
            }
            
        }

        public void TurnAbort(Object myObject, EventArgs myEventArgs)
        {
            runCycle = 0;
            tmAbort.Stop();
        }

        public void FillLinksIxbt(Object myObject, EventArgs myEventArgs)
        {
            arrLinksNew.Clear();

            SetTimerAbort();

            FuncFillLinksIxbt();

           
        }

        public void ChangeViewLinks()
        {
            
            tbMain.Inlines.Clear();

            for (int i = 0; i < arrLinksNew.Count; i++)
            {

                tbMain.Inlines.Add((Hyperlink)arrLinksNew[i]);
                tbMain.Inlines.Add("\n");
            }


        }

        public void hl_lostFocus(object sender, MouseEventArgs e)
        {
            tmLink.Stop();
        }
        public void hl_getFocus(object sender, MouseEventArgs e)
        {
           
            hlCurr = (Hyperlink)sender;
            for (int i = arrLinksNew.Count - 1; i >= 0; i--)
            {

                if ((arrLinksNew[i] as Hyperlink).NavigateUri == hlCurr.NavigateUri)
                {
                    hintCurr = i;
                    break;
                }

            }           
            SetTimerColor();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                DragMove();
        }

        public void AddArticle(string link, string name)
        {
            try
            {

            }
            catch
            {
            }


        }
        /// <summary>
        /// заполнение массива ссылок
        /// </summary>
        /// <param name="link"></param>
        /// <param name="name"></param>
        public void AddLink(string link, string name)
        {
            Link lk = new Link();
            
            lk.strLink =  link;           
            lk.strName = name;
            lk.isRead = false;
            foreach (Link item in articles.articles)
            {
                if (lk.strName == item.strName && item.isRead == true)
                {
                    lk.isRead = true;
                    break;
                }
            }
            articlesCurr.articles.Add(lk);
            //arrLinks.Add(lk);
            Run rn = new Run(lk.strName);
            
            Hyperlink hl = new Hyperlink(rn);
            hl.FontSize = 12.0;
            hl.Click += hl_Click;
            hl.MouseLeave += hl_lostFocus;
            hl.MouseEnter += hl_getFocus;
            Uri ur = new Uri(link);

            hl.NavigateUri = ur;
          
            hl.TextDecorations = new TextDecorationCollection();
            hl.ToolTip = name;

            if (lk.isRead == true)
            {
                hl.Foreground = Brushes.Black;
            }
            else
            {
                hl.Foreground = Brushes.Azure;
            }
            arrLinksNew.Add(hl);
          
        }

        public void hl_Click(object sender, RoutedEventArgs e)
        {
            Process.Start((sender as Hyperlink).NavigateUri.ToString());
        }

        private void Window_MouseEnter(object sender, MouseEventArgs e)
        {

            brdMain.Background = new LinearGradientBrush(Color.FromArgb (255, 146, 145, 145), Color.FromArgb(255, 145, 145, 145), 90);
        }

        private void Window_MouseLeave(object sender, MouseEventArgs e)
        {
            brdMain.Background = new LinearGradientBrush(Color.FromArgb(130, 255, 255, 255), Color.FromArgb(130, 0, 0, 0), 90);
        }

        private void IXBTReader_MouseMove(object sender, MouseEventArgs e)
        {
            s.FillCoordIXBT(Convert.ToInt32(IXBTReader.Left), Convert.ToInt32(IXBTReader.Top));
        }

        public void SetTimerColor()
        {
            tmLink.Interval = 300;
            tmLink.Tick += new EventHandler(ChangeColorLink);
            tmLink.Start();
        }

        public void SetTimerAbort()
        {
            tmAbort.Interval = 120000;
            tmAbort.Tick += new EventHandler(TurnAbort);
            tmAbort.Start();
            runCycle = 1;
        }

        public void FuncChangeColorLink()
        {
            Hyperlink l = (Hyperlink)arrLinksNew[hintCurr];
            l.Foreground = Brushes.Black;
            foreach (Link item in articles.articles)
            {
                if (item.strLink == l.NavigateUri.ToString())
                {
                    item.isRead = true;
                }
            }

            Serial();
        }
        public void ChangeColorLink(Object myObject, EventArgs myEventArgs)
        {
            FuncChangeColorLink();
        }

        /// <summary>
        /// записывание статей в файл
        /// </summary>
        public void Serial()
        {          
            XmlHelper.Serial(filePath, xmlName, ref articles);           

        }

        /// <summary>
        /// чтение статей из файла
        /// </summary>
        public void DeSerial()
        {

            XmlHelper.DeSerial(filePath, xmlName, ref articles);
        }    
           
        

       
    }
}
